from apps.admin import db


# 新建表Role
class Menu(db.Model):
    __tablename__ = 'fa_menu'  # 表名
    id = db.Column(db.Integer, primary_key=True)  # id字段, int 类型,主键
    name = db.Column(db.String(64))  # name字段, 字符串类型,唯一
    url = db.Column(db.String(64))  #
    icon = db.Column(db.String(64))  #
    authority = db.Column(db.String(64))  #
    checked = db.Column(db.Integer)  #
    is_menu = db.Column(db.Integer)  #
    sort = db.Column(db.Integer)  #
    parent_id = db.Column(db.Integer)  #
    createtime = db.Column(db.Integer)  #
    updatetime = db.Column(db.Integer)  #

    # users = db.relationship('User', backref = 'role', lazy = 'joined') # 外键关系

    def __init__(self, name, url, icon, authority, checked, is_menu, sort, parent_id, createtime):
        # self.id = id
        self.name = name
        self.url = url
        self.icon = icon
        self.authority = authority
        self.checked = checked
        self.is_menu = is_menu
        self.sort = sort
        self.parent_id = parent_id
        self.createtime = createtime

    def __repr__(self):  # 相当于toString
        return '<Menu %r>' % self.name

    def getListByRole(role_id=0):
        # Model = db.session.query(Menu).join(RolePermission, Permission.id==RolePermission.permission_id, isouter=True)
        Model = db.session.query(Menu)
        if role_id > 0:
            Model = Model.filter(RolePermission.role_id == role_id)
        Model = Model.group_by(Menu.id)

        total = Model.count()
        Model = Model.order_by(Menu.id.asc())

        # 打印sql
        stat = Model.statement
        print(stat)

        menu_list = Model.all()

        return menu_list, total
